
package com.easyattendance.servlets;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.User;
import com.easyattendance.services.LoginService;
import com.easyattendance.services.ValidationsService;
import com.easyattendance.util.SecurePassword;

@WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePasswordServlet"})
public class ChangePasswordServlet extends HttpServlet {


	private static final long serialVersionUID = -5858317339156979954L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	PrintWriter out = response.getWriter();
    	
    	String currentUser = (String) request.getSession().getAttribute("currentUser");
        String oldPassword=null,newPassword=null,confirmPassword=null,email_id=null;
      
        if(request.getParameter("oldpassword")!=null)
        	oldPassword = request.getParameter("oldpassword");
        //oldPassword = SecurePassword.getHashValue(oldPassword);
        if(request.getParameter("newpassword")!=null)
        	newPassword = request.getParameter("newpassword");
        if(request.getParameter("new_repassword")!=null)
        	confirmPassword = request.getParameter("new_repassword");
        
        if(request.getParameter("email")!=null)
        	email_id = request.getParameter("email");
        
        //*** Validation ***//
        LoginService loginService = new LoginService();
        ValidationsService validate = new ValidationsService();
        Boolean error_flag = false;
        String userType = loginService.getUserType(currentUser);
        String redirectTo="";
        
        //Set redirect page depending on user login.
    	if(userType.equals("Admin") || userType.equals("admin")){
    		redirectTo = "views/admin/passChange.jsp";
    	}else if(userType.equals("Section")){
    		redirectTo = "views/section/generalSettings.jsp";
    	}else if(userType.equals("Teacher")){
    		redirectTo = "views/teacher/generalSettings.jsp";
    	}
    	
        //All fields must be nonempty.
        if(oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()){
        	request.setAttribute("errorMessage", "All * fields are required.");
        	error_flag = true;
        }else{
        	if(!loginService.authenticate(currentUser, oldPassword)){
        		request.setAttribute("errorMessage", "Current password is not matched.");
        		error_flag = true;
        	}else{
        		String validatePassRes = validate.validatePassword(newPassword);
        		Boolean comparePassRes = validate.validateBothPasswords(newPassword, confirmPassword);
        		if(validatePassRes.equals("Correct")){
        			if(!comparePassRes){
        				request.setAttribute("errorMessage", "New Password and confirm passwrod do not match.");
        				error_flag = true;
        			}
        		}else{
        			request.setAttribute("errorMessage", validatePassRes);
        			error_flag = true;
        		}
        	}
        }
        
        //Send back if error with error display string.
        if(error_flag){
        	RequestDispatcher rd = request.getRequestDispatcher(redirectTo);
        	rd.forward(request, response);
        }else{    	
	    	//Check & Update query
	        boolean result = loginService.authenticatePassword(currentUser, oldPassword, newPassword);
	    	
	       
	    	
	    	if(result == true){
	    		User user=(User) loginService.getUserByUserId(email_id,"User");
	 	    	String hash_Password = SecurePassword.getHashValue(newPassword);
	 	    	loginService.updatePassword(user, hash_Password);
	    		
	    		request.setAttribute("successMessage", "Password changed successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher(redirectTo);
	        	rd.forward(request, response);
	        }
	        else{
	        	request.setAttribute("errorMessage", "Something went wrong.Try again.");
	        	RequestDispatcher rd = request.getRequestDispatcher(redirectTo);
	        	rd.forward(request, response);
	        }
        }
        
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
